$amazfit = {},$amazfit.comm = {},$amazfit.config = {},$amazfit.view = {};
/** ==============config============= */
$amazfit.config.v = "01.01.0001";
$amazfit.config.test = 0;
$amazfit.config.basePath =  "http://" + ($amazfit.config.test ? "121.43.227.180:18080/followup/" : "doctor.bb-care.com:9090/followup/");
$amazfit.config.projectName = (/\/+\w+\//gi.exec(window.location.href)+"").replace(/\//gi,"");
/** ==============AJAX================ */
$amazfit.comm.post = function(params) {
	var _success = arguments[1]?arguments[1]:params.success;
	var _error = arguments[2]?arguments[2]:params.error;
	params = $.extend({
		type:"post",
		contentType:"application/json;charset=UTF-8",
		dataType:"json",
		timeout:"10000",
		xhrFields:{
			withCredentials:!0
		},
		crossDomain:!0
	},true,params);
	params.success = function(result,success) {
		_success(true,result);
	}
	params.error = function(xhr, errorType, error,msg){
    	xhr = xhr ?xhr:{};
    	var status = {"0":$amazfit.network == "fail"?"请检查手机网络和信号，重新再试":"服务器维护中","302":"跨域请求","404":"接口不存在","400":"请求参数错误","500":"服务器错误"}
    	$amazfit.alert(status[xhr.status]).closeAll();
    	_error(false,xhr.status);
    }
	$.ajax(params);
}
$amazfit.comm.get = function(params) {
	var _success = arguments[1]?arguments[1]:params.success;
	var _error = arguments[2]?arguments[2]:params.error;
	params = $.extend({
		type:"get",
		contentType:"application/json;charset=UTF-8",
		dataType:"json",
		timeout:"10000",
        jsonpCallback:"success_jsonpCallback",
		xhrFields:{
			withCredentials:!0
		},
		crossDomain:!0
	},true,params);
	params.success = function(result,success) {
		_success(true,result);
	}
	params.error = function(xhr, errorType, error,msg){
    	xhr = xhr ?xhr:{};
    	var status = {"0":$amazfit.network == "fail"?"请检查手机网络和信号，重新再试":"服务器维护中","302":"跨域请求","404":"接口不存在","400":"请求参数错误","500":"服务器错误","200":"成功"}
    	xhr.status != "200"?$amazfit.alert(status[xhr.status]).closeAll():false;
    	_error(false,xhr.status);
    }
	$.ajax(params);
}

$amazfit.comm.Object = function(){};
$amazfit.comm.Object.extend = function(prop) {  
    var _super = this.prototype;  
    var fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
    //初始化基类（仅初始化实例，不运行构造函数）
    var initializing = true;  
    var prototype = new this();  
    initializing = false;  
    //拷贝继承对象的属性到新的对象 
    for (var name in prop) {  
      //新对象重构的属性覆盖基础对象的对应属性
      prototype[name] = typeof prop[name] == "function" &&  
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?  
        (function(name, fn){  
          return function() {  
            var tmp = this._super;  
            // 在新对象中添加一个新的 ._super() 方法 
            this._super = _super[name];  
            var ret = fn.apply(this, arguments);          
            this._super = tmp;  
            return ret;  
          };  
        })(name, prop[name]) :  
        prop[name];  
    }  
    // 构造一个继承对象 
    function Class() {   
      if ( !initializing && this.init )  
        this.init.apply(this, arguments);  
    }  
    Class.prototype = prototype;  
    Class.prototype.constructor = Class;  
    Class.extend = arguments.callee;  
    return Class;  
};
/** ==============引用全局包================ */
$amazfit.comm.importPkg = function() {
    var basePath = window.location.href;
    basePath = basePath.substring(0, basePath.indexOf($amazfit.config.projectName)+$amazfit.config.projectName.length);
    localStorage.basePath = basePath;
    $.each(arguments, function(a,b) {
	 	var url = localStorage.basePath + "/src/" + b + ".js";
        document.write("<script src='" + url + "'><\/script>");
    });
}
$amazfit.comm.setVal = function(name,value){
	if(value instanceof Object){
		value = JSON.stringify(value)
	}
	window.localStorage.setItem(name,value);
}
$amazfit.comm.getVal = function(name){
	var v = window.localStorage.getItem(name)||"";
	try{
		if(isNaN(parseInt(v,10))){
			v = eval("("+v+")");
		}
	}catch(e){
		
	}
	return v;
}
$amazfit.comm.removeVal = function(name,value){
	window.localStorage.removeItem(name);
}
$amazfit.comm.removeAll = function(){
    window.localStorage.clear();
}
$amazfit.comm.setSessionVal = function(name,value){
    window.sessionStorage.setItem(name,JSON.stringify(value));
}
$amazfit.comm.getSessionVal = function(name,value){
    return window.sessionStorage.getItem(name,value);
}
$amazfit.comm.removeSessionVal = function(name,value){
    window.sessionStorage.removeItem(name,value);
}
$amazfit.comm.daysBetween = function(DateOne, DateTwo) {
    var OneMonth = DateOne.substring(5, DateOne.lastIndexOf('/'));
    var OneDay = DateOne.substring(DateOne.length, DateOne.lastIndexOf('/') + 1);
    var OneYear = DateOne.substring(0, DateOne.indexOf('/'));
    var TwoMonth = DateTwo.substring(5, DateTwo.lastIndexOf('/'));
    var TwoDay = DateTwo.substring(DateTwo.length, DateTwo.lastIndexOf('/') + 1);
    var TwoYear = DateTwo.substring(0, DateTwo.indexOf('/'));
    var cha = ((Date.parse(OneMonth + '/' + OneDay + '/' + OneYear) - Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear)) / 86400000);
    return Math.abs(cha);
}
//获取url参数
$amazfit.comm.getUrlParam = function(name) {
    var search = document.location.search;
    var pattern = new RegExp("[?&]"+name+"\=([^&]+)", "g");
    var matcher = pattern.exec(search);
    var items = null;
    if(null != matcher){
        try{
            items = decodeURIComponent(decodeURIComponent(matcher[1]));
        }catch(e){
            try{
                items = decodeURIComponent(matcher[1]);
            }catch(e){
                items = matcher[1];
            }
        }
    }
    return items == null?false:items;
} 
//打开浮动窗口
$amazfit.comm.openIframe = function(name,src) {
    var iframe = document.createElement("iframe");
    iframe.setAttribute("id",name);
    iframe.setAttribute("src",src);
    iframe.style.position = "absolute";
    iframe.style.top = "0";
    iframe.style.left = "0";
    iframe.style.height = "100%";
    iframe.style.border = "0";
    iframe.style.padding = "0";
    document.body.appendChild(iframe);
}
//打开窗口
$amazfit.comm.open = function(){
	var _this  = this;
    _this.getParams = new Array();
    _this.params = "";
    _this.init = function(k,v){
        _this.getParams +=k +"="+v+"&";
    }
   _this.open = function(url){
		try{
    		WeixinJSBridge.invoke('getNetworkType',{}, function(e){   
				if(e.err_msg.split(":")[1] == "fail"){
					$amazfit.alert("请检查手机网络和信号，重新再试").closeAll();
				}else{
					url = url+"?"+_this.getParams+"&v=" + new Date().getTime();
					window.location=url;
				}
			})      
    	}catch(e){
    		window.location=url+"?"+_this.getParams+"&v=" + new Date().getTime();
    	}
    }
    _this.replace = function(url){
    	try{
    		WeixinJSBridge.invoke('getNetworkType',{}, function(e){   
			if(e.err_msg.split(":")[1] == "fail"){
				$amazfit.alert("请检查手机网络和信号，重新再试").closeAll();
			}else{
				 window.location.replace(url+"?"+_this.getParams);
			}
		})      
    	}catch(e){
    		 window.location.replace(url+"?"+_this.getParams);
    	}
    }
    _this.close = function(){
        window.close();
    }
}
$amazfit.alert = function(msg){
	if(msg == null||msg == "")return;
	var $container = $('<div class="bbalert" style="background: rgba(0,0,0,.6);height: 100%;width:100%;position: fixed;left:0;top:0;z-index: 1001;">');
	var $subContainer = $('<div style="display:-webkit-flex;justify-content: center;align-items: center;height: 100%;">');
	var $subTip = $('<div style="background:#fff;border-radius: .4em;width: 85%;text-align: center;margin-top: -10%;">');
	$subTip.append('<div style="padding: 1.2em 20px .5em;font-weight: 400;">温馨提示</div>');
	$subTip.append('<div style="padding: .6em 20px .5em;color:#888;word-break: break-word;">'+msg+'</div>');
	$subTip.append('<span style="border-top:1px solid #D5D5D6;width:100%;display: inline-block;height: 1px;"></span>');
	var $btn = $('<div style="text-align: center;padding:.6em 0;color:#0BB20C;cursor:pointer">确定</div>');
	$subTip.append($btn);
	$btn.bind("click",function(){
		if($btn.close){
			if($btn.close!="noclose"){
				$amazfit.setTimeout(function(){$amazfit.call($btn.close);$("body").find($container).remove()},600);
			}else{
				$btn.unbind("click");
			}
		}else{
			$("body").find($container).remove();
		}
	})
	$("body").find(".bbalert").remove();
	$container.close = function(){
		$btn.close = "close";
	}
	$container.closeAll = function(){
		$btn.close = "closeAll";
	}
	$container.reload = function(){
		$btn.close = "reload";
	}
	$container.noclose = function(){
		$btn.close = "noclose";
	}
	$("body").append($container.append($subContainer.append($subTip)));
	return $container;
}
$amazfit.alertNew = function(msg,opt){
	if(msg == null||msg == "")return;
	opt = opt||[];
	var $container = $('<div class="bbalert" style="background: rgba(0,0,0,.6);height: 100%;width:100%;position: fixed;left:0;top:0;z-index: 1001;">');
	var $subContainer = $('<div style="display:-webkit-flex;justify-content: center;align-items: center;height: 100%;">');
	var $subTip = $('<div style="background:#fff;border-radius: .4em;width: 85%;text-align: center;margin-top: -10%;position:relative">');
	$subTip.append('<div style="padding: 1.2em 20px .5em;font-weight: 600;background:#FAD1CF;color:#808080;border-radius:.4em;">提示</div>');
	var $content  = $('<div style="padding: .6em 10px .5em;color:#888;word-break: break-word;min-height:6rem;padding-top:2rem;"></div>');
	$content.append(msg);
	$subTip.append($content);
	var $btns = $('<div style="display:-webkit-flex;text-align:center;margin:1em 0;"></div>')
	var $btn1 = $('<div style="width:50%;"><span style="padding:.5rem 1rem;color:#fff;cursor:pointer;width:8rem;background:#FF6F74;display:inline-block;border-radius:.4rem;">'+(opt.left||"不更改")+'</span><div>');
	var $btn2 = $('<div style="width:50%;"><span style="padding:.5rem 1rem;color:#fff;cursor:pointer;width:8rem;background:#FF6F74;display:inline-block;border-radius:.4rem;">'+(opt.right||"确认更改")+'</span></div>');
	var $close = $("<div style='position:absolute;bottom:-7rem;left:0;color:#fff;width:100%;font-size:4rem;font-weight:800;cursor:pointer'>&times;</div>")
	$subTip.append($btns.append($btn1,$btn2),$close);
	$close.bind("click",function(){
		$("body").find($container).remove();
	})
	$container.left = function(callback){
		$btn1.bind("click",function(){
			callback($container);
		})
		return $container;
	}
	$container.right = function(callback){
		$btn2.bind("click",function(){
			callback($container);
		})
		return $container;
	}
	$("body").find(".bbalert").remove();
	$container.close = function(){
		$("body").find($container).remove();
	}
	$container.closeAll = function(){
		$amazfit.call("closeAll");
	}
	$container.reload = function(){
		$amazfit.call("reload");
	}
	$container.noclose = function(){
		$amazfit.call("noclose");
	}
	$("body").append($container.append($subContainer.append($subTip)));
	return $container;
}
$amazfit.error = function(tip){
	if(tip == null||tip == "")return;
	var $container = $("<div class='bberror' style='position:fixed;background:rgba(255,0,0,.9);color:#fff;text-align:center;padding:.5em;width:100%;top:0;z-index:999'>"+tip+"</div>");
	var timer = setTimeout(function(){
		$("body").find(".bberror").remove();
		clearTimeout(timer);
	},4000);
	$("body").find(".bberror").remove();
	$("body").append($container);
}
$amazfit.success = function(tip){
	if(tip == null||tip == "")return;
	var $container = $("<div class='bbsuccess' style='position:fixed;background:rgba(57,132,57,.9);color:#fff;text-align:center;padding:.5em;width:100%;top:0;z-index:88'>"+tip+"</div>");
	var timer = setTimeout(function(){
		$("body").find(".bbsuccess").remove();
		clearTimeout(timer);
	},4000);
	$("body").find(".bbsuccess").remove();
	$("body").append($container);
}
$amazfit.load = function(tip){
	var $container = $('<div class="bbload weui_loading_toast">');
	var $mask = $('<div class="weui_mask_transparent"></div>');
    var $toast = $('<div class="weui_toast">');       
    var $loading = $('<div class="weui_loading">');        
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_0"></div>'); 
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_1"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_2"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_3"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_4"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_5"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_6"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_7"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_8"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_9"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_10"></div>');
    $loading.append('<div class="weui_loading_leaf weui_loading_leaf_11"></div>');
    var $tip = $('<p class="weui_toast_content">'+(tip||"加载中")+'</p>');
    $container.append($mask,$toast.append($loading,$tip));
    $("body").find(".bbload").remove();
    $("body").append($container);
}
$amazfit.closeLoad = function(){
	$("body").find(".bbload").remove();
}
$amazfit.network = function(){
	try{
		WeixinJSBridge.invoke('getNetworkType',{}, function(e){   
			return e.err_msg.split(":")[1]
		})
	}catch(e){
		return !0
	}
}()

$amazfit.commitOk= function(tip){
	var $container = $('<div class="weui_toast">');
	$container.append('<i class="weui_icon_toast"></i>')
    $container.append('<p>'+tip||'已完成'+'</p>');   
    $("body").append($container);
    var timer = setTimeout(function(){
		$("body").find(".weui_toast").remove();
		clearTimeout(timer);
	},4000);
    return $container
}
$amazfit.noData  = function(tip){
	var $container = $('<div style="position: absolute;top:0;width:100%;height:100%;background: #fff;">');
	var $subcontainer = $('<div style="display:-webkit-flex;justify-content: center;align-items: center;height: 100%;">');
	var $tip = $('<div style="margin-top:-10%;text-align: center;">');
    $tip.append('<img src="../../../images/noData.png" style="width:10em;display: block;margin: 0 auto;" />');
	$tip.append('<div style="padding:1em 0;">'+(tip||"暂无数据")+'</div>')
	$("body").empty().append($container.append($subcontainer.append($tip)));
}
$amazfit.setTimeout = function(callback,time){
	var timer = setTimeout(function(){
		callback();
		clearTimeout(timer);
	},time||1000)
}
$amazfit.call = function(opt){
	var _this = this;
	_this.close = function(){
		window.history.back();
	}
	_this.closeAll = function(){
		if(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger"){
			try{
				WeixinJSBridge.call('closeWindow');
			}catch(e){
				$amazfit.alert(e).reload();
			}
		}else{
			$amazfit.alert("请在微信浏览中器打开").noclose();
		}
	}
	_this.reload = function(){
		window.location.reload();
	}
	_this[opt]?_this[opt]():0;
}
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
Date.prototype.diff = function(date){
  return (this.getTime() - date.getTime())/(24 * 60 * 60 * 1000);
}
window.isBlank = function(obj){
	return(!obj || $.trim(obj) === "");
};
